package com.origin.chaos.security.filter;

import com.origin.chaos.security.bean.LoginUser;
import com.origin.chaos.security.bean.entity.User;
import com.origin.chaos.security.serivce.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: tao.ding
 * @date 2021-07-19
 */
@Slf4j
@Component
public class UserTokenFilter extends OncePerRequestFilter {

    private IUserService userService;

    @Value("${admin.secret.key}")
    private String adminSecretKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String playUri = "/chaos/api/play", chatUri = "/chaos/api/chat";
        String manageUri = "/chaos/api/canvas-manage";
        if (uri.startsWith(playUri) || uri.startsWith(chatUri)) {
            // 用户游戏相关接口需要获取token进行处理
            String token = request.getHeader(User.TOKEN_HEADER);
            if (ObjectUtils.isEmpty(token)) {
                request.getRequestDispatcher("/not-login").forward(request, response);
                return;
            }
            LoginUser loginUser = this.userService.getLoginUserByToken(token);
            if (null == loginUser){
                request.getRequestDispatcher("/not-login").forward(request, response);
                return;
            }
            request.setAttribute(LoginUser.class.getName(), loginUser);
        } else if (uri.startsWith(manageUri)) {
            // 管理员相关接口，需要校验secret key
            String secretKey = request.getHeader("secretKey");
            if (ObjectUtils.isEmpty(secretKey) || !secretKey.equals(this.adminSecretKey)) {
                request.getRequestDispatcher("/not-admin").forward(request, response);
                return;
            }
        } else {
            // 其他接口直接放行
        }
        filterChain.doFilter(request, response);
    }

    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
